<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/


/**
 * AIR2_Record base class
 *
 * @author pkarman
 * @package default
 */
abstract class AIR2_Record extends Doctrine_Record {

    /**
     * Save the record to the database
     *
     * @param object  $conn (optional)
     */
    public function save( Doctrine_Connection $conn=null ) {
        // unless explicitly passed, we find the _master connection
        // for the current env.
        if ( $conn === null ) {
            $conn = AIR2_DBManager::get_master_connection();
        }
        parent::save($conn);
    }


    /**
     * All AIR2_Record tables should be UTF8
     */
    public function setTableDefinition() {
        // utf8 charset
        $this->option('collate', 'utf8_unicode_ci');
        $this->option('charset', 'utf8');
    }


    /**
     * Detect whether to add CreUser and UpdUser relations
     */
    public function setUp() {
        parent::setUp();

        $cols = $this->getTable()->getColumnNames();
        foreach ($cols as $name) {
            if (preg_match('/_cre_user$/', $name)) {
                $this->hasOne('UserStamp as CreUser',
                    array('local' => $name, 'foreign' => 'user_id')
                );
            }
            elseif (preg_match('/_upd_user$/', $name)) {
                $this->hasOne('UserStamp as UpdUser',
                    array('local' => $name, 'foreign' => 'user_id')
                );
            }
        }
    }



    /**
     * Custom AIR2 validation before update/save
     *
     * @param Doctrine_Event $event
     */
    public function preValidate($event) {
        air2_model_prevalidate($this);
    }


    /**
     * Determines if a record produced from the tank can be safely moved into
     * AIR2, or if it conflicts with existing AIR2 data.
     *
     * @param array   $data
     * @param TankSource $tsrc
     * @param int     $op
     */
    public function discriminate($data, &$tsrc, $op=null) {
        // update the record
        $exists = $this->exists();
        foreach ($data as $key => $val) {
            // for existing objects,  check for non-null values that will change
            if ($exists && !is_null($this->$key) && $this->$key != $val) {
                // CONFLICT!  check the $op value
                if ($op == AIR2_DISCRIM_REPLACE) {
                    $this->$key = $val;
                }
                else {
                    $cls = $this->getTable()->getClassnameToReturn();
                    $keycol = air2_get_model_uuid_col($cls);
                    $tsrc->add_conflict($cls, $key, 'Conflicting tank value', $this->$keycol);
                }
            }
            else {
                // update value... will be rolled back if we have conflicts
                $this->$key = $val;
            }
        }
    }


    /**
     * Determine if a User has permission to read this record.
     *
     * @param User    $u
     * @return authz integer
     */
    public function user_may_read(User &$u) {
        throw new Exception('user_may_read not implemented for ' . get_class($this));
        return false;
    }


    /**
     * Determine if a User has permission to write to this record.
     *
     * @param User    $u
     * @return authz integer
     */
    public function user_may_write(User &$u) {
        throw new Exception('user_may_write not implemented for ' . get_class($this));
        return false;
    }


    /**
     * Determine if a User has permission to manage this record.
     *
     * @param User    $u
     * @return authz integer
     */
    public function user_may_manage(User &$u) {
        throw new Exception('user_may_manage not implemented for ' . get_class($this));
        return false;
    }


    /**
     * Determine if a User has permission delete this record.
     * By default calls through to user_may_manage().
     *
     * @param User    $u (reference)
     * @return authz integer
     */
    public function user_may_delete(User &$u) {
        return $this->user_may_manage($u);
    }


    /**
     * Add User reading-authorization conditions to a Doctrine Query.  By
     * default, any restrictions must come from subclasses.
     *
     * @param AIR2_Query $q     (reference)
     * @param User    $u     (reference)
     * @param string  $alias (optional)
     */
    public static function query_may_read(AIR2_Query &$q, User &$u, $alias=null) {
        //TODO: alter query in subclasses
    }


    /**
     * Add User write-authorization conditions to a Doctrine Query.
     * TODO: by default, this is the same as read permissions.
     *
     * @param AIR2_Query $q     (reference)
     * @param User    $u     (reference)
     * @param string  $alias (optional)
     */
    public static function query_may_write(AIR2_Query &$q, User &$u, $alias=null) {
        self::query_may_read($q, $u, $alias);
    }


    /**
     * Add User managing-authorization conditions to a Doctrine Query.
     * TODO: by default, this is the same as write permissions.
     *
     * @param AIR2_Query $q     (reference)
     * @param User    $u     (reference)
     * @param string  $alias (optional)
     */
    public static function query_may_manage(AIR2_Query &$q, User &$u, $alias=null) {
        self::query_may_write($q, $u, $alias);
    }


}
